<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="lib/layui/css/layui.css">
    <script src="lib/layui/layui.js"></script>
    <script src="lib/js/jquery-1.12.4.js"></script>
    <script type="text/javascript" src="lib/js/cookies.js"></script>
    <script type="text/javascript" src="lib/js/functionfield.js"></script>
</head>
<body>

<script type="text/html" id="toolbarDemo">
    <form  class="layui-form">
        <div class="layui-inline">
            <label class="layui-form-label" style="width: 100px">单据日期</label>
            <div class="layui-input-block">
                <input type="text" name="date" id="date1" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label" style="width: 100px;">盘点单号:</label>
            <div class="layui-input-block">
                <input type="text" autocomplete="off" class="layui-input" id="CountOrder" value="">
            </div>
        </div>
        <div class="layui-inline">
            <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" lay-event="order">生成盘点单据</button>
            <!--<button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="history">盘点历史</button>-->
        </div>

    </form>

</script>
<fieldset class="layui-elem-field layui-field-title">
    <legend>盘点</legend>
</fieldset>

<form action="" class="layui-form layui-form-pane">
    <div class="layui-inline">
        <label class="layui-form-label">商品名称</label>
        <div class="layui-input-block">
            <input type="text" name="title" autocomplete="off" placeholder="输入商品名称/编号/助记符" class="layui-input"
                   id="productName">
        </div>
    </div>

    <div class="layui-inline">
        <label class="layui-form-label">商品状态</label>
        <div class="layui-input-inline">
            <select id="type">
                <option value="">请选择</option>
                <option value="2">已删除</option>
                <option value="3">库存为0</option>
            </select>
        </div>
    </div>

    <button type="button" class="layui-btn layui-btn-normal" data-type="reload">查询</button>
    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
    <div class="layui-inline">
        <i class="layui-icon layui-icon-about" style="font-size: 30px; color: #1E9FFF;margin-left: 10px" id="tip"></i>
    </div>

</form>
<table class="layui-hide" id="test" lay-filter="test"></table>
</body>

<script>
    layui.use(['table', 'laydate','layer','form'], function () {
        var table = layui.table;
        var form = layui.form
            , layer = layui.layer
            , laydate = layui.laydate;
        var createDate;
        var tips = "盘点完成前，请不要做出入库单据，盘点库存与查询时的系统库存比较计算盈亏。";
        var tip_index = 0;
        jQuery(document).on('mouseenter', '#tip', function () {
            tip_index = layer.tips(tips, '#tip', {time: 0, tips: [2, '#3595CC'], area: ['220px', '80px']});
        }).on('mouseleave', '#tip', function () {
            layer.close(tip_index);
        });
        table.render({
            elem: '#test',
            url: 'xp/check/getListByStock',
            toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
            defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            totalRow: true,
            title: '商品盘点',
            id: 'goodsList',
            parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": 0, //解析接口状态
                    "msg": "", //解析提示文本
                    "count": res.code, //解析数据长度
                    "data": res.obj //解析数据列表
                };
            },
            cols: [
                [
                    {
                        field: 'goodsId',
                        title: '商品编号',
                        align: 'center',
                        totalRowText: '合计'
                    }, {
                    field: 'goodsName',
                    title: '商品名称',
                    align: 'center',
                    width: 200
                }, {
                    field: 'specificationName',
                    title: '规格',
                    align: 'center',
                    templet: function (d) {
                        return "<span>" + d.specificationName + "</span>" + "<input type='hidden' class='hide' value=" + d.specificationId + ">"
                    }
                }, {
                    field: 'salesprice',
                    title: '零售价',
                    align: 'center',
                    templet: function (d) {
                        return Number(d.salesprice).toFixed(2)
                    }
                }, {
                    field: 'stock',
                    title: '库存',
                    align: 'center',
                    templet: function (d) {
                        return Number(d.stock).toFixed(2)
                    },
                    totalRow: true,

                }, {
                    field: 'checkStorage',
                    title: '盘点库存<span class="layui-badge-dot"></span>',
                    align: 'center',
                    edit: true,
                    totalRow: true
                }, {
                    field: 'Sum',
                    title: '盈亏',
                    align: 'center',
                    totalRow: true,

                }, {
                    field: 'commit',
                    title: '备注',
                    align: 'center',
                    edit: true
                }
                ]
            ],
            page: true
        });

        laydate.render({
            elem: '#date1',
            type: 'date',
            format: 'yyyy-MM-dd',
            istoday: true,
            value: new Date
        });

        table.on('edit(test)', function (obj) {
            var data = obj.data;
            var storage = data.checkStorage;
            var elem = "goodsList"; //表id
            var field = obj.field; //得到字段
            let reg = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
            if (obj.field == "checkStorage") {
                if (!(reg.test(storage))) {
                    layer.open({
                        title: '系统提示'
                        , content: '请输入有效数量'
                        , success: function (layero, index) {
                            $(document).keydown(function (event) {
                                if (event.keyCode == 13 || event.keyCode == 108) {
                                    layer.closeAll();
                                }
                            });

                        }
                    });
                    obj.update({
                        checkStorage: ""
                    })
                } else {
                    var result = (data.checkStorage - data.stock) * data.salesprice;
                    let content;
                    if (result >= 0) {
                        content = "<span style='color: #5fff1b'>" + fix(result) + "</span>";
                    } else {
                        content = "<span style='color: #e42122'>" + fix(result) + "</span>";
                    }
                    obj.tr.find("[data-field='Sum']").find(".layui-table-cell").html(content);
                    var tmp = 0.00;
                    layui.each(table.cache[elem],
                        function (inex, item) {
                            tmp += Number(item[field]);
                        });
                    $("[data-field='checkStorage']:last").find(".layui-table-cell").text(tmp.toFixed(2));
                    sum();
                }
            } else {

            }

        });

        table.on('toolbar(test)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            var data = checkStatus.data; //获取选中的数据
            if (obj.event == "order") {
                test();
            }
        });

        function format() {
            let date = new Date();
            let y = date.getFullYear().toString();
            let m = date.getMonth() + 1;
            let d = date.getDate();
            let hour = date.getHours().toString();
            let minutes = date.getMinutes().toString();
            let seconds = date.getSeconds().toString();
            let result = "Count_" + y + m.toString() + d.toString() + hour + minutes + seconds;
            $("#CountOrder").val(result);
        }

        format();
        function sum() {
            var len = $("[data-field='Sum']").length;
            var index = [];
            var stock = [];
            var result = 0.00;
            var total = 0.0000;

            for (var i = 1; i < len - 1; i++) {
                stock.push(Number($("[data-field='Sum']:eq(" + i + ")").find("span").text()));
            }
            for (var m = 0; m < stock.length; m++) {
                total += Number(stock[m]);
            }
            $("[data-field='Sum']:last").find(".layui-table-cell").text(total.toFixed(4));

        }

        function fix(obj) {
            return Number(obj).toFixed(4)
        }

        var active = {
            reload: function () {
                var content = $("#productName").val();
                var type = $("#type").val();
                if (type == 1) {
                    table.reload('goodsList', {
                        page: {
                            curr: 1
                        },
                        where: {
                            flag: type,
                            content: content
                        },
                        url: 'xp/check/getListByFlag',
                        method: 'post'
                    });
                    laydate.render({
                        elem: '#date1',
                        type: 'date',
                        format: 'yyyy-MM-dd',
                        istoday: true,
                        value: new Date
                    });
                    format();
                } else {
                    table.reload('goodsList', {
                        page: {
                            curr: 1
                        },
                        where: {
                            stock: type,
                            content: content
                        },
                        url: 'xp/check/getListByStock',
                        method: 'post'
                    });
                    laydate.render({
                        elem: '#date1',
                        type: 'date',
                        format: 'yyyy-MM-dd',
                        istoday: true,
                        value: new Date
                    });
                    format();
                }

            }
        };

        $('.layui-form .layui-btn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        function test() {
            var token = getCookie("token");
            $.post('htz/user/token',{token,token},function (res) {
                if (res!=null){
                    var type = $("#type").val();
                    var len = $("[data-field='Sum']").length;
                    var countorder = {
                        "countOrderId": $("#CountOrder").val(),
                        "staffId": res.id,
                        "createDate": $("#date1").val(),
                        "result": $("[data-field='Sum']:last").find(".layui-table-cell").text(),
                        "type": ''
                    };

                    var CountorderDetail = [];
                    var goodsId = [];
                    for (var i = 0; i < len - 2; i++) {
                        var list = {};
                        var index = $("[data-field='Sum']").find(".layui-table-cell").eq(i + 1).text();
                        if (index!='' && index !=null) {
                            list.countOrderId = $("#CountOrder").val();
                            list.goodsId = $("[data-field='goodsId']").find(".layui-table-cell").eq(i + 1).text();
                            list.goodsName = $("[data-field='goodsName']").find(".layui-table-cell").eq(i + 1).text();
                            list.specificationId = $(".hide").eq(i+1).val();
                            list.salesprice = $("[data-field='salesprice']").find(".layui-table-cell").eq(i + 1).text();
                            list.stock = $("[data-field='stock']").find(".layui-table-cell").eq(i + 1).text();
                            list.checkstock = $("[data-field='checkStorage']").find(".layui-table-cell").eq(i + 1).text();
                            list.commit = $("[data-field='commit']").find(".layui-table-cell").eq(i + 1).text();
                            CountorderDetail.push(list);
                            goodsId.push($("[data-field='goodsId']").find(".layui-table-cell").eq(i + 1).text());
                        }

                    }

                    var addCountOrderUtil  = {
                        "countorder": countorder,
                        "list": CountorderDetail,
                        "goodsList": goodsId
                    };
                    var countOrderUtil = {
                        "countorder": countorder,
                        "list": CountorderDetail
                    };

                    if(goodsId==''){
                        layer.msg("请先输入盘点库存",{icon: 2})
                    }else{
                        if(type == 2 || type == 3){
                            //console.log(type);
                            countorder.type= type;
                            $.ajax({
                                url: 'xp/check/addOrder',
                                data: JSON.stringify(countOrderUtil),
                                dataType: 'json',
                                type: 'post',
                                traditional: true,
                                contentType: 'application/json;charset=UTF-8',
                                success: function (data) {
                                    if(data.msg=="调用成功",{icon: 1}){
                                        layer.msg("盘点记录已生成");
                                    }
                                },
                                complete: function(){
                                    table.reload('goodsList',
                                        {
                                            page: {
                                                curr: 1
                                            }
                                            ,url: 'xp/check/getListByStock'
                                            ,method: 'post'
                                        });
                                    laydate.render({
                                        elem: '#date1',
                                        type: 'date',
                                        format: 'yyyy-MM-dd',
                                        istoday: true,
                                        value: new Date
                                    });
                                    format();
                                },
                                error: function () {
                                    layer.msg("后台错误",{icon: 2});
                                }

                            });
                        }else{
                            countorder.type=1;
                            // console.log(addCountOrderUtil);
                            $.ajax({
                                url: 'xp/check/addOrder',
                                data: JSON.stringify(addCountOrderUtil),
                                dataType: 'json',
                                type: 'post',
                                traditional: true,
                                contentType: 'application/json;charset=UTF-8',
                                success: function (data) {
                                    if(data.obj>0){
                                        layer.msg("盘点记录已生成",{icon: 1});
                                    }
                                },
                                complete: function(){
                                    table.reload('goodsList',
                                        {
                                            page: {
                                                curr: 1
                                            }
                                            ,url: 'xp/check/getListByStock'
                                            ,method: 'post'
                                        });
                                    laydate.render({
                                        elem: '#date1',
                                        type: 'date',
                                        format: 'yyyy-MM-dd',
                                        istoday: true,
                                        value: new Date
                                    });
                                    format();
                                },
                                error: function () {
                                    layer.msg("后台错误",{icon: 2});
                                }

                            });
                        }

                    }
                }
            })
        }
    });
</script>


</html>